package com.example.demo.dao;

import com.example.demo.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 实现查询数据库的过程
 */
@Repository
public class UserInfoDao {

    private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(UserInfoDao.class);

    @Autowired
    //从容器中自动扫描获取jdbcTemplate
    private JdbcTemplate jdbcTemplate;

    /**
     *  数据新增
     * @param userName 用户姓名
     * @param cardNo 身份证号
     * @param phoneNo 手机号
     * @param healthStatus 健康码的状态
     * @return 是否添加成功
     */
    public boolean insert(String userName,String cardNo,String phoneNo,int healthStatus){

        String SQL = "INSERT INTO `user_base` (`id`, `name`, `card_no`, `phone_no`,  `health_status`) VALUES" +
                " (NULL, ?, ?, ?, ?)";

        return jdbcTemplate.update(SQL,userName,cardNo,phoneNo ,healthStatus)>0;
    }

    //update()实现修改
    public boolean update(int id,String userName,String password){
        String sql = "update user_info set user_name=?,password=? where id=?";
        return jdbcTemplate.update(sql,userName,password,id)>0;
    }

    //查询单个值

    public User getById(Integer id) {
        String sql = "select * from user_base where id=?";
        return jdbcTemplate.queryForObject(sql, new UserInfoRowMapper(), id);
    }


    public User getByCardNo(String cardNo) {
        String sql = "select * from user_base where card_no=?";
        //RowMapper方法

        try {
            return jdbcTemplate.queryForObject(sql, new UserInfoRowMapper(), cardNo);
        } catch (DataAccessException e) {
            LOG.error("not fund data by cardNo: " + cardNo);
        }
        return null;
    }

    class UserInfoRowMapper implements RowMapper<User> {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User userInfo = new User();
            userInfo.setId(rs.getInt("id"));
            userInfo.setName(rs.getString("name"));
            userInfo.setCardNo(rs.getString("card_no"));
            userInfo.setPhoneNo(rs.getString("phone_no"));
            userInfo.setHealthStatus(rs.getInt("health_status"));
            userInfo.setRemark(rs.getString("remark"));
            userInfo.setUpdateDate(rs.getDate("update_date"));
            return userInfo;
        }
    }

    public boolean delete(int id){
        String sql = "delete from user_info where id=?";
        return jdbcTemplate.update(sql,id)>0;
    }



}
